package com.xii.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xii.constant.MessageConstant;
import com.xii.constant.RedisConstant;
import com.xii.entity.PageResult;
import com.xii.entity.QueryPageBean;
import com.xii.entity.Result;
import com.xii.pojo.Setmeal;
import com.xii.service.SetmealService;
import com.xii.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.util.UUID;

@Controller
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
    private SetmealService setmealService;

    //注入redis
    @Autowired
    private JedisPool jedisPool;

    /**
     * 新增套餐
     * @param checkgroupIds
     * @param setmeal
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Result add(Integer[] checkgroupIds,@RequestBody Setmeal setmeal){
        try {
            setmealService.add(checkgroupIds,setmeal);
            //在redis中添加已经上传的图片
            jedisPool.getResource().sadd(RedisConstant.SETMEALIMG_DB_REDIS,setmeal.getImg());
            return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
    }

    /**
     * 文件上传
     * @param imgFile 上传的文件
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Result upload(MultipartFile imgFile){
        try {
            //1、重命名
            String originalFilename = imgFile.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString()+extName;

            //2、上传到七牛云
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            //3、存储到redis  用于GC
            jedisPool.getResource().sadd(RedisConstant.SETMEALIMG_REDIS,fileName);

            return  new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }

    }

    /**
     * 分页查询
     */
    @PostMapping("/findPage")
    @ResponseBody
    public PageResult findPage(@RequestBody QueryPageBean pageBean){
        return setmealService.findPage(pageBean);
    }

}
